package com.cxm.server.config.security.component;

import com.cxm.server.pojo.Menu;
import com.cxm.server.pojo.Role;
import com.cxm.server.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 权限控制
 * 根据请求url分析请求所需的角色
 *
 * @author cxm
 */
@Component
public class CustomFilter implements FilterInvocationSecurityMetadataSource {
    @Autowired
    private MenuService menuService;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Collection<ConfigAttribute> getAttributes(Object obj) throws IllegalArgumentException {
        ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
        // 获取请求的URL
        String requestUrl = ((FilterInvocation) obj).getRequestUrl();
        List<Menu> menus = (List<Menu>) valueOperations.get("menu_with_role");
        if (CollectionUtils.isEmpty(menus)){
            menus = menuService.getMenusWithRole();
            valueOperations.set("menu_with_role",menus,12, TimeUnit.HOURS);
        }
        // 判断请求菜单url与菜单角色是否匹配
        for (Menu menu : menus) {
            if (antPathMatcher.match(menu.getUrl(), requestUrl)) {
                String[] str = menu.getRoles().stream().map(Role::getName).toArray(String[]::new);
                return SecurityConfig.createList(str);
            }
        }
        return SecurityConfig.createList("ROLE_LOGIN");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return false;
    }
}
